package com.msun.auth.apiOpen.handler;

import com.msun.auth.apiOpen.OpenContext;
import com.msun.auth.apiOpen.cache.CacheSvc;
import com.msun.auth.custom.annotation.ContextWithToken;
import com.msun.auth.custom.annotation.ResponseResult;
import com.msun.auth.custom.comdto.DataBox;
import com.msun.auth.custom.constants.RoleLevels;
import com.msun.auth.custom.exception.BizException;
import com.msun.auth.custom.exception.BizResultCode;
import com.msun.auth.database.model.MenuMo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * 类描述：
 *
 * @ClassName OpenApi
 * @Description TODO
 * @Author gj
 * @Date 2023/8/19 12:47
 * @Version 1.0
 */
@Slf4j
@Api(tags = "开放API")
@ResponseResult
@ContextWithToken
@RestController
@RequestMapping("/open/")
public class OpenApi {

    @Autowired
    private CacheSvc cacheSvc;


    @ApiOperation("接口认证")
    @ApiResponses({@ApiResponse(code = 200, message = "成功", response = OpenContext.Context.class)})
    @GetMapping("apiAuth")
    public OpenContext.Context apiAuth() {
        OpenContext.Context ctx = OpenContext.get();
        if (cacheSvc.getAppUserRoleLevel(ctx.getAppId(), ctx.getUid()) < 0) {
            throw new BizException(BizResultCode.NoRight);
        }
        return ctx;
    }

    @ApiOperation("鉴定是否可编辑")
    @ApiResponses({@ApiResponse(code = 200, message = "成功", response = DataBox.class)})
    @GetMapping("editAuth")
    public DataBox editAuth() {
        OpenContext.Context ctx = OpenContext.get();
        Integer roleLevel = cacheSvc.getAppUserRoleLevel(ctx.getAppId(), ctx.getUid());
        if (roleLevel < 0) {
            throw new BizException(BizResultCode.NoRight);
        }
        return DataBox.of(roleLevel >= RoleLevels.READ_WRITE);
    }

    @Data
    public static class GetMenuListDto {
        private List<MenuMo> menuList;
    }

    @ApiOperation("获取菜单列表")
    @ApiResponses({@ApiResponse(code = 200, message = "成功", response = GetMenuListDto.class)})
    @GetMapping("getMenuList")
    public GetMenuListDto getMenuList() {
        OpenContext.Context ctx = OpenContext.get();
        if (cacheSvc.getAppUserRoleLevel(ctx.getAppId(), ctx.getUid()) < 0) {
            throw new BizException(BizResultCode.NoRight);
        }
        GetMenuListDto dto = new GetMenuListDto();
        dto.setMenuList(cacheSvc.getAppUserMenuList(ctx.getAppId(), ctx.getUid()));
        return dto;
    }
}